import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:zl_widgets_kit/zl_widgets_kit.dart';

class InheritedWidgetData<T> extends InheritedWidget {
  const InheritedWidgetData({
    Key? key,
    required Widget child,
    required this.data,
  }) : super(key: key, child: child);

  final T data;
  @override
  bool updateShouldNotify(InheritedWidgetData<T> oldWidget) {
    return true;
  }
}

class MyInheritedWidget extends StatefulWidget {
  MyInheritedWidget({
    Key? key,
    required this.child,
  }) : super(key: key);

  final Widget child;

  @override
  _MyInheritedWidgetState createState() => _MyInheritedWidgetState();

  static _MyInheritedWidgetState of(BuildContext context, {bool rebuild = true}) {
    if (rebuild) {
      return context.dependOnInheritedWidgetOfExactType<InheritedWidgetData<_MyInheritedWidgetState>>()!.data;
    }
    return context.findAncestorWidgetOfExactType<InheritedWidgetData<_MyInheritedWidgetState>>()!.data;
  }
}

class _MyInheritedWidgetState extends State<MyInheritedWidget> {
  int counter = 0;

  void _incrementCounter() {
    setState(() {
      counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return InheritedWidgetData(
      data: this,
      child: widget.child,
    );
  }
}













class WidgetA extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final _MyInheritedWidgetState state = MyInheritedWidget.of(context);
    return Center(
      child: Text(
        '${state.counter}',
        style: Theme.of(context).textTheme.headline2,
      ),
    );
  }
}

class WidgetB extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Text('I am a widget that will not be rebuilt.');
  }
}

class WidgetC extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final _MyInheritedWidgetState state = MyInheritedWidget.of(context, rebuild: false);
    return ZLButton("点击修改数据", bgColor: Colors.limeAccent, callback: () {
      state._incrementCounter();
    });
  }
}
